package list;

import java.lang.reflect.Array;

/**
 * Created by zlb on 2017/3/8.
 */
public class SeqList<E> implements ILinarList<E> {
    private int maxsize;
    private E[]date;
    private int size;

    /**
     * 初始化数组
     * @param type
     * @param maxsize
     */
    @SuppressWarnings("unchecked")
    public SeqList(Class<E> type, int maxsize){
        this.maxsize = maxsize;
        date= (E[]) Array.newInstance(type,maxsize);
        size =0;
    }

    /**
     * 增添元素
     * @param item
     * @return
     */
    @java.lang.Override
    public boolean add(E item) {
        if (!isFull()){
            date[size++]=item;
            return true;
        }
        return false;
    }

    /**
     * 增添到指定位置
     * @param i
     * @param e
     * @return
     */
    @java.lang.Override
    public boolean add(int i, E e) {
        if (i<0 ||i>size){
            throw  new IndexOutOfBoundsException("Index:"+i+",Size:"+size);
        }
        if (!isFull()){
            for (int j = size-1;j>=i;j--){
                date[j+1]=date[j];
            }
            date[i]=e;
            size++;
            return true;
        }
        return false;
    }

    @java.lang.Override
    public E remove(int i) {
        rangeCheck(i);
        if (!isEmpty()){
            E oldValue = date[i];
            for (int j=i;j<size-1;j++){
                date[j]=date[j+1];
            }
            date[--size]=null;
            return oldValue;
        }
        return null;
    }

    @java.lang.Override
    public int indexOf(E item) {
        if (item==null){
            for (int i=0; i<size;i++){
                if (date[i]==null){
                    return i;
                }
            }
        }else {
            for (int i=0;i<size;i++){
                if (item.equals(date[i])){
                    return i;
                }
            }
        }
        return -1;
    }

    @java.lang.Override
    public E get(int i) {
        rangeCheck(i);

        return date[i];
    }

    @java.lang.Override
    public int size() {
        return size;
    }

    @java.lang.Override
    public void clear() {
    for (int i=0;i<size;i++){
        date[i]=null;
    }
        size=0;
    }

    @java.lang.Override
    public boolean isEmpty() {

        return size==0;
    }

    @java.lang.Override
    public void rangeCheck(int i) {
        if (i<0|| i>=size){
            throw  new IndexOutOfBoundsException("Index:"+i+",Size:"+size);
        }
    }

    @java.lang.Override
    public boolean isFull() {
        if (size==maxsize){
            return true;
        }
        return false;
    }
}
